﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Imaging;

namespace intTrans
{
    class MedianFilter
    {
        private Bitmap BitPic, newBmp;
        private int windowsize;
        private int ha;
        private List<int> r = new List<int>();
        private List<int> g = new List<int>();
        private List<int> b = new List<int>();

        public MedianFilter(string filename, string wsze)
        {
            string[] ws = wsze.Split('x');
            windowsize = int.Parse(ws[0]);
            BitPic = new Bitmap(filename);
            if (BitPic.PixelFormat == PixelFormat.Format8bppIndexed)
            {
                newBmp = new Bitmap(BitPic.Width, BitPic.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                using (Graphics gfx = Graphics.FromImage(newBmp))
                {
                    gfx.DrawImage(BitPic, 0, 0);
                }
                BitPic = newBmp;
            }
        }

        public Bitmap Transform(ProgressBar progbar)
        {
            int x, y;
            ha = windowsize / 2;
            progbar.Maximum = BitPic.Width;
            progbar.Value = 0;
            for (x = ha; x < BitPic.Width - ha; x++)
            {
                for (y = ha; y < BitPic.Height - ha; y++)
                {
                    r.Clear();
                    g.Clear();
                    b.Clear();
                    for (int i = 0; i < windowsize * windowsize; i++)
                    {
                        Unsorted(x, y, i);
                    }

                    /*kernel rendezés*/
                    r.Sort();
                    g.Sort();
                    b.Sort();

                    /*pixel frissítése*/
                    BitPic.SetPixel(x, y, Color.FromArgb(r[r.Count / 2], g[g.Count / 2], b[b.Count / 2]));
                }
                progbar.Value++;
            }
            return BitPic;
        }

        /*kernel feltöltése*/
        public void Unsorted(int x, int y, int index)
        {
            r.Add((BitPic.GetPixel(x + (index % windowsize) - ha, y + (index / windowsize) - ha)).R);
            g.Add((BitPic.GetPixel(x + (index % windowsize) - ha, y + (index / windowsize) - ha)).G);
            b.Add((BitPic.GetPixel(x + (index % windowsize) - ha, y + (index / windowsize) - ha)).B);
        }
    }
}
